/** 
 * 初始化elmentui表单字段配置
*/

export async function setFormItemConfigs(fieldsConfig: Array<fieldConfig>) {
    let isShowFormRuleDescription = false;
    let formItemConfigs: Array<formItemConfigType> = [];
    for (let item of fieldsConfig) {
        if (item.isShow && !item.isDefaultValue) {
            const formItemConfig: formItemConfigType = {
                formItemLabel: item.fieldName,
                elItem: item.fieldType as elItemType,
                vModelfield: item.fieldCode,
                ruleDescription: item.fieldRuleDescription,
                prop: item.fieldCode,
                attributesBind: {},
                fieldRule: []
            };

            isShowFormRuleDescription = isShowFormRuleDescription || !!item.fieldRuleDescription;

            // ElDateTimePicker处理
            if (item.fieldType === 'ElDateTimePicker') {
                formItemConfig.elItem = 'ElDatePicker';
                formItemConfig.attributesBind!.type = 'datetime';
            }

            // input框类型校验（字符串）
            if (item.fieldPattern) {
                formItemConfig.fieldRule!.push({
                    pattern: item.fieldPattern,
                    message: '请输入正确格式',
                    trigger: 'blur'
                });
            } else if (item.fieldContentType) {
                if (item.fieldContentType === 'number' || item.fieldContentType === 'float' || item.fieldContentType === 'integer') {
                    // 该部分是为了优化v-model.number的不足
                    // 独立验证数字类型的格式，
                    // 其绑定的字段的值其实是string类型
                    // 即便如此我们在编辑及新增时做了类型转化处理，保证前后端类型验证的通过
                    formItemConfig.fieldRule!.push({
                        type: item.fieldContentType,
                        validator: validateChange,
                        trigger: 'change'
                    });
                } else {
                    formItemConfig.fieldRule!.push({
                        type: item.fieldContentType,
                        trigger: 'change'
                    });
                }
            }

            // 必传组件处理
            if (item.isRequired) {
                formItemConfig.fieldRule!.push({
                    required: true,
                    message: `请输入${item.fieldName}`,
                    trigger: 'blur'
                });
            }

            // 处理需要option的组件
            if (
                item.fieldType === 'ElCheckboxGroup' ||
                item.fieldType === 'ElRadioGroup' ||
                item.fieldType === 'ElSelect' ||
                item.fieldType === 'ElTreeSelect'
            ) {
                formItemConfig.optionConfigs = await getOptions(item.optionDataApi as string);
            }

            // 文件上传配置
            if (item.fieldType === 'ElImgList' || item.fieldType === 'ElUpload') {
                formItemConfig.uploadAllowFile = item.uploadAllowFile;
            }

            formItemConfigs.push(formItemConfig);
        }
    }
    return {
        isShowFormRuleDescription,
        formItemConfigs
    };
}

// 自定义数字校验规则
const validateChange = (rule: any, value: any, callback: any) => {
    const numberValue = Number(value);
    const stringValue = String(value);
    if (numberValue) {
        if (rule.type === 'number') {
            if (typeof numberValue === 'number') {
                callback();
            } else {
                callback(new Error('请输入正确格式的数值'));
            }
            return;
        }
        if (rule.type === 'float') {
            if (typeof numberValue === 'number') {
                callback();
            } else {
                callback(new Error('请输入正确格式的数值'));
            }
            return;
        }
        if (rule.type === 'integer') {
            if (
                typeof numberValue === 'number' &&
                Number.isInteger(numberValue) &&
                !stringValue.includes('.')
            ) {
                callback();
            } else {
                callback(new Error('请输入正确格式的数值'));
            }
            return;
        }
        callback();
    } else {
        if (isNaN(numberValue) && typeof value !== 'undefined') {
            callback(new Error('请输入正确格式的数值'));
            return;
        }
        callback();
    }
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
const getOptions = async (url: string, data: any = {}) => {
    // TODO: 接入数据获取接口
    // try {
    //     const res: any = await request({
    //         url,
    //         method: 'post',
    //         data
    //     });
    //     if (res.code === 200) {
    //         return res.data;
    //     } else {
    //         ElMessage.error('选项接口参数错误，请联系管理员！！！');
    //         throw new Error('选项接口参数错误：' + url);
    //     }
    // } catch (error) {
    //     ElMessage.error('选项接口错误，请联系管理员！！！');
    //     throw new Error('选项接口错误：' + url);
    // }
    return [
        {
            value: 'chengdu',
            label: '成都'
        },
        {
            value: 'shenzhen',
            label: '深圳'
        },
        {
            value: 'guangzhou',
            label: '广州'
        },
        {
            value: 'dalian',
            label: '大连'
        }
    ];
};
